package com.iking.housekeeping.controller.servicestaff;

import java.util.Date;
import java.util.List;
import javax.validation.Valid;

import com.iking.housekeeping.entity.dept.SysDept;
import com.iking.housekeeping.httpbean.elderlyreq.HttpElderlyReq;
import com.iking.housekeeping.httpbean.servicerecord.HttpVisitedRecord;
import com.iking.housekeeping.redis.RedisObjectService;
import com.iking.housekeeping.service.dept.DeptService;
import com.iking.housekeeping.service.user.LoginService;
import com.iking.housekeeping.util.token.WebTokenUtil;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.github.pagehelper.Page;
import com.iking.housekeeping.common.CodeEnum;
import com.iking.housekeeping.common.PageResult;
import com.iking.housekeeping.common.ReturnCode;
import com.iking.housekeeping.entity.servicestaff.ServiceStaff;
import com.iking.housekeeping.httpbean.elderlyres.ElderlyRes;
import com.iking.housekeeping.httpbean.servicestaff.reqbean.DetailsServiceStaff;
import com.iking.housekeeping.httpbean.servicestaff.reqbean.SelectServiceRes;
import com.iking.housekeeping.httpbean.servicestaff.reqbean.StaffBySelect;
import com.iking.housekeeping.service.elderly.ElderlyService;
import com.iking.housekeeping.service.servicestaff.ServiceStaffService;
import com.iking.housekeeping.util.DateUtil;
import com.iking.housekeeping.util.MessageDigest5;
import com.iking.housekeeping.util.UUIDUtil;


/**
 * 服务人员
 * 
 * @author: gf
 * @date: 2018年4月18日 下午5:35:17
 */
@RestController
@RequestMapping("/serviceStaff")
public class ServiceStaffController {

	/**
	 * 服务人员操作
	 */
	@Autowired
	private ServiceStaffService serviceStaffService;	
	
	@Autowired
	private ElderlyService elderlyService;

	@Autowired
	private DeptService deptService;

	@Autowired
	private RedisObjectService<String> redisObjectService;

	@Autowired
	private LoginService loginService;
	/**
	 * 	添加服务人员
	 *  @param req
	 *  @return ReturnCode
	 *  @author gf
	 */
	@PostMapping("/insert")
	public ReturnCode insert(@RequestBody @Valid ServiceStaff req, BindingResult bindingResult) {
		//验证参数
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			
			return new ReturnCode(CodeEnum.FAIL_EARROR_PARM, msg, null);
		}
		//验证姓名是否带有空格
		if(req.getfName().contains(" ")) {
			return new ReturnCode(CodeEnum.FAIL, "姓名不能带有空格！", null);
		}
		//验证身份证号是否带有空格
		if(req.getfCardId().contains(" ")) {
			return new ReturnCode(CodeEnum.FAIL, "身份证含有空格", null);
		}
		//验证电话是否带有空格
		if(req.getfPhone().contains(" ")) {
			return new ReturnCode(CodeEnum.FAIL, "电话不能带有空格！", null);
		}
		//只存放身份证的对象
		ServiceStaff serviceStaff = new ServiceStaff();
		serviceStaff.setfCardId(req.getfCardId().trim());
		//验证身份证号是否重复
		if (serviceStaffService.selectRepeat(serviceStaff) != null) {	
			return new ReturnCode(CodeEnum.FAIL, "身份证号已存在", null);
		}
		serviceStaff.setfCardId(null);
		serviceStaff.setfPhone(req.getfPhone().trim());
		if(serviceStaffService.selectRepeat(serviceStaff) != null) {
			return new ReturnCode(CodeEnum.FAIL, "手机号已存在", null);
		}
		//设置UUId
		req.setfId(UUIDUtil.getUUID());
		req.setfIsDelete(false);
		req.setfPassword(MessageDigest5.md5(req.getfPassword()));
		//执行方法
		Integer result = serviceStaffService.insert(req);
		if(result == null || result == 0) {
			return new ReturnCode(CodeEnum.FAIL);
		}
		return new ReturnCode(CodeEnum.SUCCESS);
	}
	
	/**
	 * 	批量删除服务人员
	 *  @param list
	 *  @return ReturnCode
	 *  @author gf
	 */
	@PostMapping("/deleteBatch")
	public ReturnCode deleteBatch(@RequestBody List<String> list) {
		//查询正在服务或已预约的人员信息
		List<String> serviceStaffListNo = serviceStaffService.selectStaffBySelectList(list);
		if(serviceStaffListNo.size() > 0) {
			String msg = StringUtils.join(serviceStaffListNo.toArray(), ",") + "有正在进行或已预约的服务，不可删除！";
			return new ReturnCode(CodeEnum.FAIL, msg, null);
		}
		//查询有没有负责的老人
		List<String> elderlyList = elderlyService.selectByServiceStaffList(list);
		if(elderlyList.size() > 0) {
			return new ReturnCode(CodeEnum.FAIL, "服务人员中有负责的老人，不可删除！", null);
		}
		for (int i = 0; i < list.size(); i++) {
			String id=redisObjectService.get("webToken:" +list.get(i));
			if(id!=null){
				return new ReturnCode(CodeEnum.FAIL, "正在登录的用户不能删除！", null);
			}
		}

		int result = serviceStaffService.deleteBatch(list);
		if(result == 0) {
			return new ReturnCode(CodeEnum.FAIL, "删除失败", null);
		}
		elderlyService.deleteBatch(list);
		return new ReturnCode(CodeEnum.SUCCESS);
	}
	/**
	 * 	修改服务人员
	 *  @param req
	 *  @return ReturnCode
	 *  @author gf
	 */
	@PostMapping("/update")
	public ReturnCode update(@RequestBody @Valid ServiceStaff req, BindingResult bindingResult) {
		//验证参数
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			return new ReturnCode(CodeEnum.FAIL, msg, null);
		}
		//验证姓名是否带有空格
		if(req.getfName().contains(" ")) {
			return new ReturnCode(CodeEnum.FAIL, "姓名不能带有空格！", null);
		}
		//验证身份证号是否带有空格
		if(req.getfCardId().contains(" ")) {
			return new ReturnCode(CodeEnum.FAIL, "身份证含有空格", null);
		}
		//数据库查出的对象
		ServiceStaff serviceStaffInfo = serviceStaffService.selectByPrimaryKey(req.getfId());
		//只存放身份证的对象
		ServiceStaff serviceStaff = new ServiceStaff();
		serviceStaff.setfCardId(req.getfCardId().trim());
		//验证身份证号是否重复
		if (serviceStaffInfo != null) {
			if (!serviceStaffInfo.getfCardId().equals(req.getfCardId())) {
				ServiceStaff staff = serviceStaffService.selectRepeat(serviceStaff);
				if(staff!=null) {
					return new ReturnCode(CodeEnum.FAIL, "身份证号已存在", null);
				}
			} else if (!serviceStaffInfo.getfPhone().equals(req.getfPhone())) {
				serviceStaff.setfCardId(null);
				serviceStaff.setfPhone(req.getfPhone().trim());
				ServiceStaff staff = serviceStaffService.selectRepeat(serviceStaff);
				if(staff!=null) {
					return new ReturnCode(CodeEnum.FAIL, "手机号已存在", null);
				}
			}
		}
		//验证电话是否带有空格
		if(req.getfPhone().contains(" ")) {
			return new ReturnCode(CodeEnum.FAIL, "手机号不能带有空格！", null);
		}
		//执行方法
		req.setfPassword(MessageDigest5.md5(req.getfPassword()));
		req.setfGmtModified(new Date());
		Integer result = serviceStaffService.update(req);
		if(result == null || result == 0) {
			return new ReturnCode(CodeEnum.FAIL);	
		}
		return new ReturnCode(CodeEnum.SUCCESS);
	}
	
	/**
	 * 	服务人员信息展示
	 *  @param staffBySelect
	 *  @return ReturnCode
	 *  @author gf
	 */
	@PostMapping("/selectAll")
	public ReturnCode selectAll(@RequestBody StaffBySelect staffBySelect, javax.servlet.http.HttpServletRequest request) {
		// 获取当前登录人id
		String userId = WebTokenUtil.getUserIdByRequest(request);
		List<SysDept> menuList = deptService.selectAdminById(userId);
		int result=loginService.select(staffBySelect.getfStreetCommunity(),menuList);
		if(result==0){
			return new ReturnCode(CodeEnum.FAIL,"您没有该区域查看权限！", null);
		}else if(result==1){
			staffBySelect.setfStreetCommunity(menuList.get(0).getfId());
		}else if(result==2){
			staffBySelect.setfStreetCommunity(menuList.get(0).getfId());
		}else if(result==3){
			staffBySelect.setfStreetCommunity(menuList.get(0).getfId());
		}
		Page<SelectServiceRes> page = serviceStaffService.selectAll(staffBySelect,request);
		return new ReturnCode(CodeEnum.SUCCESS, new PageResult<SelectServiceRes>(page));
	}
	/**
	 * 通过id查询详情
	 *  @param fId
	 *  @return ReturnCode
	 *  @author gf
	 */
	@GetMapping("/selectById/{fId}")
	public ReturnCode selectById(@PathVariable("fId") String fId) {
		DetailsServiceStaff detailsServiceStaff = serviceStaffService.selectById(fId);
		return new ReturnCode(CodeEnum.SUCCESS,detailsServiceStaff );
	}
/**
	 * 
	 * @Description:查询服务人员的当前服务
	 * @author:CGZ
	 * @param request
	 * @return
	 */
	@GetMapping("/currentService")
	public ReturnCode selectCurrentService(HttpServletRequest request){
		ElderlyRes serviceElderly = serviceStaffService.selectCurrentService(request);
		if(serviceElderly == null) {
			return new ReturnCode(CodeEnum.SUCCESS, null);
		}
		return new ReturnCode(CodeEnum.SUCCESS,serviceElderly);
	}
	/**
	 * 
	 * @Description:上传服务图片
	 * @author:CGZ
	 * @param request
	 * @param file
	 * @return
	 */
	@PostMapping("/uploadimage")
	public ReturnCode uploadimage(HttpServletRequest request, @RequestParam("file")MultipartFile file){
		return new ReturnCode(CodeEnum.SUCCESS, serviceStaffService.uploadImage(file));
	}

//	@PostMapping("/giveServiceStaffByIDAndType")
//	public ReturnCode giveServiceStaffByIDAndType(@RequestBody  @Valid StaffBySelect staffBySelect, BindingResult bindingResult ){
//		//验证参数
//		if (bindingResult.hasErrors()) {
//			String msg = bindingResult.getFieldError().getDefaultMessage();
//			return new ReturnCode(CodeEnum.FAIL, msg, null);
//		}
//		List<ServiceStaff> list =serviceStaffService.giveServiceStaffByIDAndType(staffBySelect);
////		if (list.size()<0){
////			return new ReturnCode(CodeEnum.SUCCESS, null);
////		}
//		return new ReturnCode(CodeEnum.SUCCESS,list);
//	}

	/**
	 * 根据老人所在区域和服务类型获取该服务人员所分配的老人
	 * @param record
	 * @return  List<HttpGiveElderly>
	 */
	@PostMapping("/selectElderlyInfo")
	public ReturnCode selectElderlyInfo (@RequestBody @Valid HttpElderlyReq record, BindingResult bindingResult){
		if(record.getfQuantumTimeBegin() != null) {
			record.setfQuantumTimeBegin(DateUtil.addStartTime(record.getfQuantumTimeBegin()));
		}
		if(record.getfQuantumTimeEnd() != null) {
			record.setfQuantumTimeEnd(DateUtil.getDayAfter(DateUtil.addStartTime(record.getfQuantumTimeEnd())));
		}
		List<HttpElderlyReq> httpElderlyReqs=serviceStaffService.selectElderlyInfo(record);
		return new ReturnCode(CodeEnum.SUCCESS,httpElderlyReqs);
	}

	/**
	 * 获取当前登录人信息
	 * @param request
	 * @return  DetailsServiceStaff
	 */
	@PostMapping("/ElderlyInfo")
	public ReturnCode ElderlyInfo (javax.servlet.http.HttpServletRequest request){
		// 获取当前登录人id
		String userId = WebTokenUtil.getUserIdByRequest(request);
		DetailsServiceStaff detailsServiceStaff=serviceStaffService.selectById(userId);
		if (detailsServiceStaff==null){
			return new ReturnCode(CodeEnum.FAIL,  null);
		}
		return new ReturnCode(CodeEnum.SUCCESS,detailsServiceStaff);
	}
}
